import React, { useEffect } from 'react';
import { Tabs } from 'antd';
import { useNavigate } from 'react-router-dom';
import { useTabsStore } from '@/store/tabs';

const TabsBar: React.FC = () => {
  const navigate = useNavigate();
  const { tabs, activeKey, removeTab, setActiveTab } = useTabsStore();

  useEffect(() => {
    // 调试信息已清理
  }, [tabs, activeKey]);

  const handleTabChange = (key: string) => {
    setActiveTab(key);
    const tab = tabs.find(t => t.key === key);
    if (tab) {
      navigate(tab.path);
    }
  };

  const handleTabEdit = (targetKey: string | React.MouseEvent | React.KeyboardEvent, action: 'add' | 'remove') => {
    if (action === 'remove' && typeof targetKey === 'string') {
      removeTab(targetKey);
    }
  };

  const tabItems = tabs.map(tab => ({
    key: tab.key,
    label: tab.label,
    closable: tab.closable !== false,
  }));

  return (
    <div
      style={{
        backgroundColor: '#fff',
        boxShadow: '0 1px 4px rgba(0, 21, 41, 0.08)',
        zIndex: 999,
        minHeight: '40px',
        borderBottom: '1px solid #f0f0f0',
      }}
    >
      {tabs.length > 0 ? (
        <Tabs
          activeKey={activeKey || '/dashboard'}
          onChange={handleTabChange}
          onEdit={handleTabEdit}
          type="editable-card"
          hideAdd
          items={tabItems}
          size="small"
          style={{
            margin: 0,
            padding: '12px 16px', // 统一的上下左右padding
            // 覆盖Ant Design Tabs的默认margin-bottom
          }}
          // 覆盖Ant Design Tabs组件的默认样式
          className="custom-tabs"
        />
      ) : (
        <div style={{ padding: '12px 16px', color: '#999', fontSize: '14px' }}>
          暂无打开的标签页 - 请从左侧菜单选择页面
        </div>
      )}
    </div>
  );
};

export default TabsBar;